"use strict";
$jq.namespace('PeopleMedia.CP');

PeopleMedia.CP.LoginRegistrationManager = function () {
    this._geoMgr = null;
    this._regMgr = null;
    this._loginMgr = null;
    this._profileMgr = null;
    this._duplicateEmailOnSisterSiteLoginMgr = null;
    this._loginRegistrationPanelId = "divLoginRegistration";
    this._geoScriptLoaded = false;
    this._loginScriptLoaded = false;
    this._registrationScriptLoaded = false;
    this._profileScriptLoaded = false;
    this._onQuestionDisplay = null;
    this._onReady = null;
    this.SIGNUP_FLOW_TYPE_REGISTRATION_FIRST = 0;
    this.SIGNUP_FLOW_TYPE_SINGLE_PROFILE_QUESTIONS_FIRST = 1;
    this._signupFlowType = this.SIGNUP_FLOW_TYPE_REGISTRATION_FIRST;
    this._profilePage = null;
    this._defaultProfileOptionListType = 1;
};

PeopleMedia.CP.LoginRegistrationManager.prototype = {
    Oid: "PeopleMedia.CP.LoginRegistrationManager-v1.2",
    loginMgr: function () {
        return this._loginMgr;
    },
    regMgr: function () {
        return this._regMgr;
    },
    profileMgr: function () {
        return this._profileMgr;
    },
    geoMgr: function () {
        return this._geoMgr;
    },
    onSuccess: function (onSuccess) {
        try {
            this.loginMgr().OnLoginSuccess(onSuccess);
            this.regMgr().OnRegistrationSuccess(onSuccess);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"onSuccess" });
        }
    },
    loginRegistrationPanelId: function (loginRegistrationPanelId) {
        if (arguments.length > 0) {
            this._loginRegistrationPanelId = loginRegistrationPanelId;
        } else {
            return this._loginRegistrationPanelId;
        }
    },
    loginRegistrationPanel: function () {
        return $jq("#" + this._loginRegistrationPanelId);
    },
    onQuestionDisplay: function (onQuestionDisplay) {
        if (arguments.length > 0) {
            this._onQuestionDisplay = onQuestionDisplay;
        } else {
            return this._onQuestionDisplay;
        }
    },
    onReady: function (onReady) {
        if (arguments.length > 0) {
            this._onReady = onReady;
        } else {
            return this._onReady;
        }
    },
    signupFlowType: function (signupFlowType) {
        if (arguments.length > 0) {
            this._signupFlowType = signupFlowType;
        } else {
            return this._signupFlowType;
        }
    },
    profilePage: function (profilePage) {
        if (arguments.length > 0) {
            this._profilePage = profilePage;
        } else {
            return this._profilePage;
        }
    },
    defaultProfileOptionListType: function (defaultProfileOptionListType) {
        if (arguments.length > 0) {
            this._defaultProfileOptionListType = defaultProfileOptionListType;
        } else {
            return this._defaultProfileOptionListType;
        }
    },
    initialize: function (signupFlowType) {
        try {
            if (signupFlowType != undefined && signupFlowType != null) {
                this._signupFlowType = signupFlowType;
            }
            var vcRoot = FRONT_SITE_URL;
            var thisObj = this;
            var startTime = new Date().getTime();
            var url = vcRoot + "www/js/js1/geo-v1.0.js";
			
            var timeoutValue = 60000;
            PeopleMedia.CP.onReady(function () {
                jQuery.ajax({
                    url: url,
                    dataType: "script",
                    success: function () {
                        thisObj._geoScriptLoaded = true;
                        thisObj.onScriptLoaded();
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var endTime = new Date().getTime();
                        var duration = (endTime - startTime);
                        var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                        if (!data.IsCancelled) {
                            PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "initialize geo", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                            });
                        }
                    },
                    cache: true,
                    timeout: timeoutValue
                });
                var startTime2 = new Date().getTime();
                var url2 = vcRoot + "www/js/js1/login-v1.1.js";
                jQuery.ajax({
                    url: url2,
                    dataType: "script",
                    success: function () {
                        thisObj._loginScriptLoaded = true;
                        thisObj.onScriptLoaded();
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var endTime2 = new Date().getTime();
                        var duration2 = (endTime2 - startTime2);
                        var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                        if (!data.IsCancelled) {
                            PeopleMedia.CP.logAjaxError("Ajax request failure", url2, { oid: thisObj.Oid, method: "initialize login", duration: duration2 }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                            });
                        }
                    },
                    cache: true,
                    timeout: timeoutValue
                });
                var startTime3 = new Date().getTime();
                var url3 = vcRoot + "www/js/js1/registration-v1.3.js";
                jQuery.ajax({
                    url: url3,
                    dataType: "script",
                    success: function () {
                        thisObj._registrationScriptLoaded = true;
                        thisObj.onScriptLoaded();
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var endTime3 = new Date().getTime();
                        var duration3 = (endTime3 - startTime3);
                        var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                        if (!data.IsCancelled) {
                            PeopleMedia.CP.logAjaxError("Ajax request failure", url3, { oid: thisObj.Oid, method: "initialize registration", duration: duration3 }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                            });
                        }
                    },
                    cache: true,
                    timeout: timeoutValue
                });
                var startTime4 = new Date().getTime();
                var url4 = vcRoot + "www/js/js1/profile-v1.0.js";
                jQuery.ajax({
                    url: url4,
                    dataType: "script",
                    success: function () {
						
                        thisObj._profileScriptLoaded = true;
                        thisObj.onScriptLoaded();
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var endTime4 = new Date().getTime();
                        var duration4 = (endTime4 - startTime4);
                        var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                        if (!data.IsCancelled) {
                            PeopleMedia.CP.logAjaxError("Ajax request failure", url4, { oid: thisObj.Oid, method: "initialize profile", duration: duration4 }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                            });
                        }
                    },
                    cache: true,
                    timeout: timeoutValue
                });

                PeopleMedia.CP.addEnterKeyAction('divDuplicateEmailOnSisterSite', 'btnDuplicateEmailOnSisterSiteLogin');
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initialize" });
        }
    },
    onScriptLoaded: function (name) {
        try {
            if (this._geoScriptLoaded && this._loginScriptLoaded && this._registrationScriptLoaded && this._profileScriptLoaded) {
			
                this.completeInitialization();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"onScriptLoaded" });
        }
    },
    completeInitialization: function () {
        try {
            this._geoMgr = new PeopleMedia.CP.GeoManager();
            this._regMgr = new PeopleMedia.CP.RegistrationManager();
            this._loginMgr = new PeopleMedia.CP.LoginManager();
            this._profileMgr = new PeopleMedia.CP.ProfileManager();

            var thisObj = this;
            this.regMgr().OnQuestionDisplay(function () {
                thisObj.regMgr_onQuestionDisplay();
            });

            this.loginMgr().initialize();
            this.regMgr().initialize();

            if (PeopleMedia.CP.ProfileManager != undefined) {
                this._profileMgr = new PeopleMedia.CP.ProfileManager();
                this.profileMgr().OnQuestionDisplay(function () {
                    thisObj.profileMgr_onQuestionDisplay();
                });
                if (this._signupFlowType == this.SIGNUP_FLOW_TYPE_REGISTRATION_FIRST) {
                    this.initializeSignupFlowTypeRegistrationFirst();
                } else {
                    this.initializeSignupFlowTypeSingleProfileQuestionsFirst();
                }
            }
            if (this._onReady != null) {
                this._onReady(this);
            }
			this.profileMgr().loadQuestions();
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"completeInitialization" });
        }
    },
    initializeSignupFlowTypeRegistrationFirst: function () {
        try {
            // handle duplicate email address on sister site
            this.regMgr().OnRegistrationFailure(
                function (sender, errors) {
                    var isUsernameTakenError = false;
                    var isDuplicateEmailOnSisterSiteError = false;
                    var isDuplicateEmailUsernameAndPasswordOnSisterSiteError = false;
                    var sisterSiteID = 0;
                    var sisterSiteName = "";
                    for (var i = 0; i < errors.length; ++i) {
                        if (errors[i].Code == "UsernameTaken") {
                            isUsernameTakenError = true;
                        } else if (errors[i].Code == "DuplicateEmailAddressOnSisterSite") {
                            isDuplicateEmailOnSisterSiteError = true;
                            sisterSiteID = errors[i].SisterSiteID;
                            sisterSiteName = errors[i].SisterSiteName;
                        } else if (errors[i].Code == "DuplicateEmailAddressUsernameAndPasswordOnSisterSite") {
                            isDuplicateEmailUsernameAndPasswordOnSisterSiteError = true;
                            sisterSiteID = errors[i].SisterSiteID;
                            sisterSiteName = errors[i].SisterSiteName;
                        }
                    }
                    if (thisObj.hasDuplicateEmailOnSisterSite() && isDuplicateEmailOnSisterSiteError) {
                        thisObj.showDuplicateEmailOnSisterSite(sisterSiteID, sisterSiteName, false);
                    } else if (thisObj.hasDuplicateEmailOnSisterSite() && isDuplicateEmailUsernameAndPasswordOnSisterSiteError) {
                        thisObj.showDuplicateEmailOnSisterSite(sisterSiteID, sisterSiteName, true);
                    } else if (isUsernameTakenError && $jq("#divRegistrationUsernameTaken").length > 0) {
                        thisObj.regMgr().validateUsernameAndPassword(function (errors, validationData) {
                            if (thisObj.regMgr().isUsernameTakenValidationError(validationData)) {
                                thisObj.handleUsernameTakenValidationError(validationData);
                            } else {
                                thisObj.regMgr().standardOnRegistrationFailure(sender, errors);
                            }
                        });
                    } else if (!isUsernameTakenError && $jq("#divRegistrationUsernameTaken:visible").length > 0) {
                        thisObj.regMgr().hideAllPanels();
                        PeopleMedia.CP.Messaging.reset();
                        thisObj.regMgr().CurrentPanelNumber(thisObj.regMgr().PanelCount());
                        thisObj.regMgr().showPanel(thisObj.regMgr().CurrentPanelNumber());
                        thisObj.regMgr().standardOnRegistrationFailure(sender, errors);
                    } else {
                        thisObj.regMgr().standardOnRegistrationFailure(sender, errors);
                    }
                });

            if (this.profileMgr() != null) {
                this.regMgr().loadQuestions();
                var thisObj = this;
                this.regMgr().OnRegistrationSuccess(
                    function (sender, regData) {
                        PeopleMedia.CP.Services.invoke({
                            method: 'AuthenticateWithMemberInfo',
                            data: { "siteId": PeopleMedia.CP.SiteID(), "username": regData.NickName, "password": thisObj.regMgr().Password(), "genderId": regData.Gender, "emailAddress": regData.EmailAddress, "visitorId": PeopleMedia.CP.VisitorID() },
                            async: false,
                            success: function (result) {
                                try {
                                    if (result && result.redirect) {
                                        location.href = result.redirect;
                                    } else {
                                        if (thisObj.profilePage() != null) {
                                            if (PeopleMedia.CP.gotoLpsPage) {
                                                PeopleMedia.CP.gotoLpsPage(thisObj.profilePage());
                                            } else {
                                                PeopleMedia.CP.gotoSite("/v3/lps?cpp=" + thisObj.profilePage());
                                            }
                                        } else if (thisObj.profileMgr().ProfilePanel().length > 0) {
                                            PeopleMedia.CP.MemberID(regData.Identifier);
                                            PeopleMedia.CP.EncodedMemberID(regData.EncodedIdentifier);
                                            thisObj.profileMgr().loadQuestions();
                                            thisObj.loginRegistrationPanel().fadeOut('fast', function() {
                                                thisObj.profileMgr().ProfilePanel().fadeIn('slow', function() {
                                                    if (this.style.removeAttribute) {
                                                        this.style.removeAttribute('filter');
                                                    }
                                                });
                                            });
                                            PeopleMedia.CP.Messaging.reset();
                                        } else {
                                            thisObj.regMgr().standardOnRegistrationSuccess(sender, regData);
                                        }
                                    }
                                }
                                catch (ex) {
                                    PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initializeSignupFlowTypeRegistrationFirst OnRegistrationSuccess" });
                                }
                            }
                        });
                    });
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initializeSignupFlowTypeRegistrationFirst" });
        }
    },
    initializeSignupFlowTypeSingleProfileQuestionsFirst: function () {
        try {
            var thisObj = this;

            // not starting with registration questions, so hide the registration panel and show the profile panel
            this.loginRegistrationPanel().hide();
            this.profileMgr().ProfilePanel().show();

            // use list boxes rather than dropdowns for profile questions
            this.profileMgr().DefaultOptionListType(this.defaultProfileOptionListType());

            // don't include 'choose' in the dropdown options
            this.profileMgr().AddChooseOptionToResponses(false);

            // start with gender question (it's a registration question so we have to handle it as a special case to show it first)
            if (typeof(PeopleMedia.CP.GenderSeekEnabled()) !== 'undefined' && PeopleMedia.CP.GenderSeekEnabled() != null && PeopleMedia.CP.GenderSeekEnabled()) {
                this.profileMgr().InitialQuestions([
                  { "QuestionID": 999, "QuestionText": "Gender",
                      Responses: [
                          { "ResponseID": 12, "ResponseText": "Man seeking women" },
                          { "ResponseID": 21, "ResponseText": "Woman seeking men" },
                          { "ResponseID": 11, "ResponseText": "Man seeking men" },
                          { "ResponseID": 22, "ResponseText": "Woman seeking women" }
                      ]
                  }]);
                this.profileMgr().addQuestionTextOverride(999, "You are:");
            } else {
                this.profileMgr().InitialQuestions([
                  { "QuestionID": 13, "QuestionText": "Gender",
                      Responses: [
                          { "ResponseID": 1, "ResponseText": "Male" },
                          { "ResponseID": 2, "ResponseText": "Female" }
                      ]
                  }]);            
                this.profileMgr().addQuestionTextOverride(13, "You are:");
            }

            // override question & response text
            this.profileMgr().addQuestionTextOverride(1, "What color is your hair?");
            this.profileMgr().addQuestionTextOverride(2, "What color are your eyes?");
            this.profileMgr().addQuestionTextOverride(19, "How tall are you?");
            this.profileMgr().addQuestionTextOverride(101, "What is your ethnicity?");
            this.profileMgr().addQuestionTextOverride(4, "What is your body type?");
            this.profileMgr().addQuestionTextOverride(100, "How would you describe your looks?");
            this.profileMgr().addQuestionTextOverride(5, "What is your marital status?");
            this.profileMgr().addQuestionTextOverride(16, "How many children do you have?");
            this.profileMgr().addQuestionTextOverride(17, "Number of children living with me:");
            this.profileMgr().addQuestionTextOverride(98, "Do you smoke?");

            this.profileMgr().addResponseTextOverride(1, 7, "What hair?");

            // exclude height 4'0" - 4'4"
            for (var i = (4 * 12); i < (4 * 12 + 5); ++i) {
                this.profileMgr().excludeResponse(19, i.toString());
            }

            // exclude height 6'6" - 7'11"
            //for (var i = (6 * 12 + 6); i < (8 * 12); ++i) {
            //    this.profileMgr().excludeResponse(19, i.toString());
            //}

            // exclude # children, 10+
            this.profileMgr().excludeResponse(16, "10");

            // exclude # children living with me, 10+
            this.profileMgr().excludeResponse(17, "10");

            // set the profile questions panel count for the profile questions (1 panel per question)
            this.profileMgr().OnQuestionsLoaded(function (sender, questions) {
                thisObj.profileMgr().PanelCount(questions.length);
                thisObj.fireOnQuestionDisplay();
            });

            var onQuestionDisplay = this._onQuestionDisplay; // don't fire this event until profile questions loaded
            this._onQuestionDisplay = null;

            var regMgrOnQuestionDisplay = this.regMgr().OnQuestionDisplay();
            this.regMgr().OnQuestionDisplay(null);

            // load the registration questsion so we know how many there are for the percent complete
            this.regMgr().loadQuestions();
            this.regMgr().PanelCount(this.regMgr().Questions().length);

            this._onQuestionDisplay = onQuestionDisplay;
            this.regMgr().OnQuestionDisplay(regMgrOnQuestionDisplay);

            this.regMgr().OnRegistrationFailure(function (sender, errors) {
                if (errors != null && errors.length > 0 && errors[0].Code == "DuplicateEmailAddress") {
                    errors = [{ Field: thisObj.regMgr().EmailAddressFieldname(), Text: 'Sorry, an account has already been registered to that email address. <a href="' + PeopleMedia.CP.getSiteUrl('/v3/forgotpassword') + '" target="_blank">Click here</a> to go to &quot;<a href="' + PeopleMedia.CP.getSiteUrl('/v3/forgotpassword') + '" target="_blank">Forgot Password</a>&quot; and the username and password will be emailed to you.'}];
                    thisObj.regMgr().CurrentPanelNumber(thisObj.regMgr().PanelCount());
                    thisObj.regMgr().showPanel(thisObj.regMgr().CurrentPanelNumber());
                    thisObj.regMgr().standardOnRegistrationFailure(sender, errors);
                }
                else if (errors != null && errors.length > 0 && errors[0].Code == "UsernameTaken" && $jq("#divRegistrationUsernameTaken").length > 0) {
                    thisObj.regMgr().validateUsernameAndPassword(function (errors, validationData) {
                        if (thisObj.regMgr().isUsernameTakenValidationError(validationData)) {
                            thisObj.handleUsernameTakenValidationError(validationData);
                        } else {
                            thisObj.regMgr().standardOnRegistrationFailure(sender, errors);
                        }
                    });
                }
                else if (thisObj.hasDuplicateEmailOnSisterSite()) {
                    var isDuplicateEmailOnSisterSiteError = false;
                    var isDuplicateEmailUsernameAndPasswordOnSisterSiteError = false;
                    var sisterSiteID = 0;
                    var sisterSiteName = "";
                    for (var i = 0; i < errors.length; ++i) {
                        if (errors[i].Code == "DuplicateEmailAddressOnSisterSite") {
                            isDuplicateEmailOnSisterSiteError = true;
                            sisterSiteID = errors[i].SisterSiteID;
                            sisterSiteName = errors[i].SisterSiteName;
                        } else if (errors[i].Code == "DuplicateEmailAddressUsernameAndPasswordOnSisterSite") {
                            isDuplicateEmailUsernameAndPasswordOnSisterSiteError = true;
                            sisterSiteID = errors[i].SisterSiteID;
                            sisterSiteName = errors[i].SisterSiteName;
                        }
                    }
                    if (isDuplicateEmailOnSisterSiteError) {
                        thisObj.showDuplicateEmailOnSisterSite(sisterSiteID, sisterSiteName, false);
                    } else if (isDuplicateEmailUsernameAndPasswordOnSisterSiteError) {
                        thisObj.showDuplicateEmailOnSisterSite(sisterSiteID, sisterSiteName, true);
                    } else {
                        thisObj.regMgr().standardOnRegistrationFailure(sender, errors);
                    }
                } else {
                    thisObj.regMgr().standardOnRegistrationFailure(sender, errors);
                }
            });

            // load and display the questions
            this.profileMgr().loadQuestions();

            // handle the pre-submit event to instead load the regigration queastions
            this.profileMgr().OnQuestionsPreSubmit(function (sender, questions) {
                if (PeopleMedia.CP.MemberID() == null || PeopleMedia.CP.MemberID() <= 0) {
                    // combined gender is presented during the profile question stage, so we must inject it into the registration stage
                    var profileGenderCombinedResponseFieldname = thisObj.profileMgr().ResponseFieldnamePrefix() + "999";
                    if ($jq('#' + profileGenderCombinedResponseFieldname).length > 0) {
                        if ($jq('#' + thisObj.regMgr().GenderCombinedFieldname()).length > 0) {
                            $jq('#' + thisObj.regMgr().GenderCombinedFieldname()).val($jq('#' + profileGenderCombinedResponseFieldname).val());
                        } else {
                            var responseGenderCombinedElementHtml = "<select id='" + thisObj.regMgr().GenderCombinedFieldname() + "' name='" + thisObj.regMgr().GenderCombinedFieldname() + "' style='display:none;'>";
                            responseGenderCombinedElementHtml += "<option value='12'>Man seeking women</option>";
                            responseGenderCombinedElementHtml += "<option value='21'>Woman seeking men</option>";
                            responseGenderCombinedElementHtml += "<option value='11'>Man seeking men</option>";
                            responseGenderCombinedElementHtml += "<option value='22'>Woman seeking women</option>";                            
                            responseGenderCombinedElementHtml += "</select>";
                            responseGenderCombinedElementHtml += "<input type='hidden' id='" + thisObj.regMgr().GenderFieldname() + "' name='" + thisObj.regMgr().GenderFieldname() + "' />";
                            responseGenderCombinedElementHtml += "<input type='hidden' id='" + thisObj.regMgr().GenderSeekFieldname() + "' name='" + thisObj.regMgr().GenderSeekFieldname() + "' />";
                            thisObj.regMgr().RegistrationPanel().append(responseGenderCombinedElementHtml);
                            $jq('#' + thisObj.regMgr().GenderCombinedFieldname()).val($jq('#' + profileGenderCombinedResponseFieldname).val());
                        }
                        
                        var profileGenderCombinedResponseFieldValue = $jq('#' + profileGenderCombinedResponseFieldname).val();
                        if ($jq('#' + thisObj.regMgr().GenderFieldname()).length > 0 && profileGenderCombinedResponseFieldValue.length == 2) {
                            $jq('#' + thisObj.regMgr().GenderFieldname()).val(profileGenderCombinedResponseFieldValue.substr(0,1));
                        }
                        if ($jq('#' + thisObj.regMgr().GenderSeekFieldname()).length > 0 && profileGenderCombinedResponseFieldValue.length == 2) {
                            $jq('#' + thisObj.regMgr().GenderSeekFieldname()).val(profileGenderCombinedResponseFieldValue.substr(1,1));
                        }                            
                    } else {
                        // gender is presented during the profile question stage, so we must inject it into the registration stage
                        var profileGenderResponseFieldname = thisObj.profileMgr().ResponseFieldnamePrefix() + "13";
                        if ($jq('#' + profileGenderResponseFieldname).length > 0) {
                            if ($jq('#' + thisObj.regMgr().GenderFieldname()).length > 0) {
                                $jq('#' + thisObj.regMgr().GenderFieldname()).val($jq('#' + profileGenderResponseFieldname).val());
                            } else {
                                var responseElementHtml = "<select id='" + thisObj.regMgr().GenderFieldname() + "' name='" + thisObj.regMgr().GenderFieldname() + "' style='display:none;'>";
                                responseElementHtml += "<option value='1'>Male</option>";
                                responseElementHtml += "<option value='2'>Female</option>";
                                responseElementHtml += "</select>";
                                thisObj.regMgr().RegistrationPanel().append(responseElementHtml);
                                $jq('#' + thisObj.regMgr().GenderFieldname()).val($jq('#' + profileGenderResponseFieldname).val());
                            }
                        }
                    }
                    
                    thisObj.profileMgr().ProfilePanel().hide();
                    thisObj.loginRegistrationPanel().show();
                    thisObj.regMgr().loadQuestions();
                    thisObj.loginMgr().LoginPanel().hide();
                    thisObj.regMgr().RegistrationPanel().show();
                    return false;
                } else {
                    return true;
                }
            });

            // when the registration is successful, submit the profile questions
            this.regMgr().OnRegistrationSuccess(function (sender, regData) {
                PeopleMedia.CP.MemberID(regData.Identifier);
                PeopleMedia.CP.EncodedMemberID(regData.EncodedIdentifier);
                thisObj.profileMgr().OnQuestionsSubmitted(function () {
                    PeopleMedia.CP.Services.invoke({
                        method: 'AuthenticateWithMemberInfo',
                        data: { "siteId": PeopleMedia.CP.SiteID(), "username": regData.NickName, "password": thisObj.regMgr().Password(), "genderId": regData.Gender, "emailAddress": regData.EmailAddress, "visitorId": PeopleMedia.CP.VisitorID() },
                        async: false,
                        success: function (result) {
                            try {
                                if (result && result.redirect) {
                                    location.href = result.redirect;
                                } else {
                                    if (thisObj.profileMgr().NextPage() == null) {
                                        PeopleMedia.CP.gotoCPPage("/site/landingpages/shared/essay-02.html");
                                    } else {
                                        PeopleMedia.CP.gotoCPPage(thisObj.profileMgr().NextPage());
                                    }
                                }
                            }
                            catch (ex) {
                                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initializeSignupFlowTypeSingleProfileQuestionsFirst OnRegistrationSuccess" });
                            }
                        }
                    });
                });
                thisObj.profileMgr().submit();
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initializeSignupFlowTypeSingleProfileQuestionsFirst" });
        }
    },
    handleUsernameTakenValidationError: function (validationData) {
        try {
            for (var i = 0; i < 3; ++i) {
                if (i < validationData.AlternativeUsernames.length && validationData.AlternativeUsernames[i].length > 0) {
                    $jq("#divRegistrationUsername" + (i + 1).toString()).show();
                    $jq("#rdoRegistrationUsername" + (i + 1).toString()).attr('value', validationData.AlternativeUsernames[i]);
                    $jq("#lblRegistrationUsername" + (i + 1).toString()).html(validationData.AlternativeUsernames[i]);
                } else {
                    $jq("#divRegistrationUsername" + (i + 1).toString()).hide();
                }
            }
            $jq("#txtRegistrationNewUsername").val(this.regMgr().Username());
            this.regMgr().hideAllPanels();
            PeopleMedia.CP.Messaging.reset();
            this.regMgr().CurrentPanelNumber(this.regMgr().PanelCount());
            $jq("#divRegistrationUsernameTaken").show();
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"handleUsernameTakenValidationError" });
        }
    },
    showSigninView: function () {
        try {
            var thisObj = this;
            if ($jq("#" + thisObj.profileMgr().ProfilePanelId() + ":visible").length > 0) {
                thisObj.profileMgr().ProfilePanel().fadeOut('fast', function () {
                    thisObj.regMgr().RegistrationPanel().hide();
                    thisObj.loginMgr().LoginPanel().show();
                    thisObj.loginRegistrationPanel().fadeIn('slow', function () {
                        if (this.style.removeAttribute) {
                            this.style.removeAttribute('filter');
                        }
                    });
                });
            }
            else if ($jq("#" + thisObj.regMgr().RegistrationPanelId() + ":visible").length > 0) {
                thisObj.regMgr().RegistrationPanel().fadeOut('fast', function () {
                    thisObj.loginMgr().LoginPanel().fadeIn('slow', function () {
                        if (this.style.removeAttribute) {
                            this.style.removeAttribute('filter');
                        }
                    });
                });
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showSigninView" });
        }
    },
    showSignupView: function () {
        try {
            var thisObj = this;
            this.loginRegistrationPanel().fadeOut('fast', function () {
                thisObj.profileMgr().showPanel(1);
                thisObj.profileMgr().ProfilePanel().fadeIn('slow', function () {
                    if (this.style.removeAttribute) {
                        this.style.removeAttribute('filter');
                    }
                });
                thisObj.initialize(thisObj._signupFlowType);
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showSignupView" });
        }
    },
    showNextPanel: function () {
        try {
            if ($jq("#" + this.profileMgr().ProfilePanelId() + ":visible").length > 0) {
                this.profileMgr().showNextPanel();
            } else if ($jq("#" + this.regMgr().RegistrationPanelId() + ":visible").length > 0) {
                this.regMgr().showNextPanel();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showNextPanel" });
        }
    },
    showPreviousPanel: function () {
        try {
            if ($jq("#" + this.profileMgr().ProfilePanelId() + ":visible").length > 0) {
                this.profileMgr().showPreviousPanel();
            } else if ($jq("#" + this.regMgr().RegistrationPanelId() + ":visible").length > 0) {
                if (this.regMgr().CurrentPanelNumber() == 1) {
                    this.loginRegistrationPanel().hide();
                    this.profileMgr().ProfilePanel().show();
                    this.profileMgr_onQuestionDisplay();
                } else {
                    this.regMgr().showPreviousPanel();
                }
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showPreviousPanel" });
        }
    },
    showZipPostalCodeCityStatePanel: function(countryCode) {
        if(typeof(countryCode) !== 'undefined') {
            $jq('#'+this.regMgr().CountryCodeFieldname()).val(countryCode);
        }
        this.regMgr().updateZipPostalCodeLabel();
        this.regMgr().showZipPostalCodeCityState();
        this.showNextPanel();
    },
    profileMgr_onQuestionDisplay: function () {
        try {
            if (this.profileMgr().CurrentPanelNumber() == 1) {
                $jq('.divProfilePrevious').hide();
            } else {
                $jq('.divProfilePrevious').show();
            }
            var val = this.profileMgr().getCurrentQuestionValue();
            if (val != undefined && val != null && val.length > 0) {
                $jq('.divProfileNext').show();
            } else {
                $jq('.divProfileNext').hide();
            }
            this.fireOnQuestionDisplay();
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"profileMgr_onQuestionDisplay" });
        }
    },
    regMgr_onQuestionDisplay: function () {
        try {
            var thisObj = this;
            $jq('.divProfilePrevious').show();
            this.regMgr().validateCurrentQuestion(function (errors) {
                if (errors == null || errors.length <= 0) {
                    $jq('.divProfileNext').show();
                } else {
                    $jq('.divProfileNext').hide();
                }
            },
            function (errors) {
                if (errors == null || errors.length <= 0) {
                    $jq('.divProfileNext').show();
                } else {
                    $jq('.divProfileNext').hide();
                }
            });
            thisObj.fireOnQuestionDisplay();
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"regMgr_onQuestionDisplay" });
        }
    },
    fireOnQuestionDisplay: function () {
        try {
            if (this._onQuestionDisplay != undefined && this._onQuestionDisplay != null) {
                this._onQuestionDisplay();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"fireOnQuestionDisplay" });
        }
    },
    percentComplete: function () {
        try {
            if (this._signupFlowType == this.SIGNUP_FLOW_TYPE_SINGLE_PROFILE_QUESTIONS_FIRST) {
                if ($jq("#" + this.profileMgr().ProfilePanelId() + ":visible").length > 0) {
                    return 100.0 * this.profileMgr().CurrentPanelNumber() / (this.profileMgr().PanelCount() + this.regMgr().PanelCount() + 1);
                } else {
                    return 100.0 * (this.profileMgr().PanelCount() + this.regMgr().CurrentPanelNumber()) / (this.profileMgr().PanelCount() + this.regMgr().PanelCount() + 1);
                }
            }
            else {
                return 0;
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"percentComplete" });
            return 0;
        }
    },
    hasDuplicateEmailOnSisterSite: function () {
        try {
            return $jq("#divDuplicateEmailOnSisterSite").length;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"hasDuplicateEmailOnSisterSite" });
            return false;
        }
    },
    showDuplicateEmailOnSisterSite: function (sisterSiteID, sisterSiteName, duplicateUsernameAndPassword) {
        try {
            if (this._duplicateEmailOnSisterSiteLoginMgr == null) {
                this._duplicateEmailOnSisterSiteLoginMgr = new PeopleMedia.CP.LoginManager();
                this._duplicateEmailOnSisterSiteLoginMgr.UsernameFieldname("txtDuplicateEmailOnSisterSiteUsername");
                this._duplicateEmailOnSisterSiteLoginMgr.PasswordFieldname("txtDuplicateEmailOnSisterSitePassword");
                this._duplicateEmailOnSisterSiteLoginMgr.LoginButtonFieldname("btnDuplicateEmailOnSisterSiteLogin");
                this._duplicateEmailOnSisterSiteLoginMgr.initialize();
            }

            if (duplicateUsernameAndPassword) {
                $jq("#txtDuplicateEmailOnSisterSiteUsername").val(this.regMgr().Username());
                $jq("#txtDuplicateEmailOnSisterSitePassword").val(this.regMgr().Password());
                $jq("#txtDuplicateEmailOnSisterSiteUsername").attr('disabled', 'disabled');
                $jq("#txtDuplicateEmailOnSisterSitePassword").attr('disabled', 'disabled');
            } else {
                $jq("#txtDuplicateEmailOnSisterSiteUsername").val("");
                $jq("#txtDuplicateEmailOnSisterSitePassword").val("");
                $jq("#txtDuplicateEmailOnSisterSiteUsername").removeAttr('disabled');
                $jq("#txtDuplicateEmailOnSisterSitePassword").removeAttr('disabled');
            }

            //var panel = $jq("#divDuplicateEmailOnSisterSite");
            //if (panel.css("position") == "absolute") {
            //    var top = ($jq(window).height() / 2) - (panel.height() / 2);
            //    var left = ($jq(window).width() / 2) - (panel.width() / 2);
            //    panel.css("top", top);
            //    panel.css("left", left);
            //}

            if (this._signupFlowType == this.SIGNUP_FLOW_TYPE_SINGLE_PROFILE_QUESTIONS_FIRST) {
                if ($jq("#divDuplicateEmailOnSisterSiteTitle").length > 0) {
                    $jq("#txtTitle").html($jq("#divDuplicateEmailOnSisterSiteTitle").html());
                }
                $jq("#funnel_bar_container").hide();
            }

            // last-minute hack to handle incorrect casing in company table
            if (sisterSiteName == "seniorpeoplemeet.com") {
                sisterSiteName = "SeniorPeopleMeet.com";
            }

            $jq(".clsSisterSiteName").each(function () {
                $jq(this).html(sisterSiteName);
            });

            PeopleMedia.CP.Messaging.reset();
            //divProfile
            if ($jq("#" + this.loginRegistrationPanelId() + ":visible").length > 0) {
                this.loginRegistrationPanel().fadeOut('fast', function () {
                    $jq("#divDuplicateEmailOnSisterSite").fadeIn('fast', function () {
                        if (this.style.removeAttribute) {
                            this.style.removeAttribute('filter');
                        }
                    });
                });
            } else if ($jq("#divProfile:visible").length > 0) {
                $jq("#divProfile").fadeOut('fast', function () {
                    $jq("#divDuplicateEmailOnSisterSite").fadeIn('fast', function () {
                        if (this.style.removeAttribute) {
                            this.style.removeAttribute('filter');
                        }
                    });
                });
            } else {
                $jq("#divDuplicateEmailOnSisterSite").fadeIn('fast', function () {
                    if (this.style.removeAttribute) {
                        this.style.removeAttribute('filter');
                    }
                });
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showDuplicateEmailOnSisterSite" });
        }
    }
};
